package cn.agilean.test.rest;

import cn.agilean.test.entity.Company;
import cn.agilean.test.entity.Product;
import cn.agilean.test.repo.ProductRepo;
import cn.agilean.test.service.CompanyManager;
import cn.agilean.test.service.ProductManager;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/products")
public class ProductApi {
    @Resource
    private ProductManager productManager;

    @Resource
    private CompanyManager companyManager;

    @Resource
    private ProductRepo productRepo;

    public ProductApi(ProductManager productManager) {
        this.productManager = productManager;
    }

    /**
     * test-1 按productId获取商品信息
     */

    @GetMapping("/getProductInfoByProductId/{productId}")
    public Object getProductInfoByProductId(@PathVariable String productId) {
        if (productId == null || "".equals(productId)) {
            return "查询条件productId为空";
        }
        Product productInfoByProductId = productManager.getProductInfoByProductId(productId);
        if (productInfoByProductId == null) {
            return "产品信息为空";
        }
        Company conmanyInfoByCompanyId = companyManager.getConmanyInfoByCompanyId(productInfoByProductId.getCompanyId());
        JSONObject jsonObject = new JSONObject();
        Map toJsonMap = new HashMap();
        toJsonMap.put("id", productInfoByProductId.getId());
        toJsonMap.put("name", productInfoByProductId.getName());
        toJsonMap.put("price", productInfoByProductId.getPrice());
        toJsonMap.put("company", conmanyInfoByCompanyId);
        String toJSONString = jsonObject.toJSONString(toJsonMap);
        return toJSONString;
    }



    @GetMapping("/getProductByBlackList")
    private Object getProductByBlackList() {
        List<JSONObject> resp=new ArrayList<>();
        for (Product product : productRepo.getProducts()) {
            String productId=product.getId();
            if (productManager.isBlackList(productId)) {
                continue;
            }

            Product productInfo = productManager.getProductInfoByProductId(productId);
            if (productInfo == null) {
                return null;
            }
            Company companyInfo = companyManager.getConmanyInfoByCompanyId(productInfo.getCompanyId());
            JSONObject productJson = new JSONObject();
            productJson.put("id", productInfo.getId());
            productJson.put("name", productInfo.getName());
            productJson.put("price", productInfo.getPrice());
            productJson.put("company", companyInfo);
            resp.add(productJson);
        }


        return resp;
    }
}
